<?php
/**
 * CreateTime: 2024/1/15 16:31
 * User:LinQ
 */

namespace App\Func\Wx;

use App\ApiCall\Wx\Applet\WxAppletExecute;
use Illuminate\Support\Facades\Redis;

class WxAppletFunc
{
    public function getStableAccessToken(){
        $force_refresh =  config('openapi.wx.applet.get_access_token_type');
        $key = config('openapi.wx.applet.wx_access_token_key');
        // 若不为强刷新模式 则先尝试从缓存中读取accessToken
        if(!$force_refresh){
            $ttl = Redis::ttl($key);
            if(!$ttl||$ttl<=300){
                $res = (new WxAppletExecute())->getStableAccessToken();
                $fmtRes = json_decode($res->body());
                if(isset($fmtRes->errcode) && $fmtRes->errcode!=0){
                    s_fail_return(null,$fmtRes->errmsg);
                }
                Redis::setex($key, $fmtRes->expires_in, $fmtRes->access_token);
                return $fmtRes->access_token;
            }else{
                return Redis::get($key);
            }
        }
        $res = (new WxAppletExecute())->getStableAccessToken();
        $fmtRes = json_decode($res->body());
        if(isset($fmtRes->errcode) && $fmtRes->errcode!=0){
            s_fail_return(null,$fmtRes->errmsg);
        }
        return $fmtRes->access_token;
    }
}